package com.itheima.httpClient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URL;

/**
 * HttpClient方式发送请求
 */
public class Client_Get {
    public static void main(String[] args) throws Exception {
        //确定请求地址
        String url1 = "http://www.itcast.cn";
        //转换为URL对象
        URL url = new URL(url1);
        //创建一个httpClient对象(由于是接口,没办法创建对象,所以利用实现类)
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //设置请求方式为GET
        HttpGet httpGet = new HttpGet(url1);
        //设置请求头
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36");
        //设置请求参数

        //发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取响应状态码
        int code = response.getStatusLine().getStatusCode();
        if (code == 200){
            //响应成功
            //获取响应头
            Header[] headers = response.getHeaders("Content-Type");
            String value = headers[0].getValue();
            System.out.println(value);//这里获取的是第一个

            //获取响应体
            HttpEntity entity = response.getEntity();
            //这里只适用于返回的是字符串类型的
            String html = EntityUtils.toString(entity, "UTF-8");
            System.out.println(html);
        }
        httpClient.close();

    }
}
